#include "SendGameMessage.h"
#include "GameMessage.h"
#include "Socket.h"
#include "Factory.h"
#include "ServerManager.h"

#include <iostream>

bool SendGameMessage(GameMessage& gm, Socket* s)
{
	if (!s->IsOpen())
	{
		return false;
	}

	SocketMessage sm;
	gm.Write(&sm);

	return s->Send(sm);
}

GameMessage* ReceiveGameMessage(Socket* s)
{
	if (!s->IsOpen())
	{
		return nullptr;
	}
	
	// read the type of game message we want to create
	SocketMessage sm;
	if (!s->Receive(&sm))
	{
		//std::cout << "Failed to receive game message" << std::endl;
		return nullptr;
	}
	//std::cout << "Received a game message" << std::endl;
	std::string gmType;
	if (!sm.ReadString(&gmType))
	{
		//std::cout << "Failed to recieve gm type" << std::endl;
		return nullptr;
	}
	std::cout << "Received gm type: " + gmType << std::endl;
	// create it (factory)
	GameMessage* gm = TheGameMessageFactory::Instance()->Create(gmType);
	if (!gm)
	{
		std::cout << "Failed to create gm" << std::endl;
		return nullptr;
	}

	// game message loads itself
	if (!gm->Read(&sm))
	{
		std::cout << "failed to read gm" << std::endl;
		return nullptr;
	}

	// return the game message

	return gm;
}